package com.haynes.meetxiaohai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haynes.meetxiaohai.common.PublicKey;
import com.haynes.meetxiaohai.dto.DishDto;
import com.haynes.meetxiaohai.service.CategoryService;
import com.haynes.meetxiaohai.service.DishFlavorService;
import com.haynes.meetxiaohai.service.DishService;
import com.haynes.meetxiaohai.common.R;
import com.haynes.meetxiaohai.entity.Category;
import com.haynes.meetxiaohai.entity.Dish;
import com.haynes.meetxiaohai.entity.DishFlavor;
import com.sun.istack.internal.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @Author Haynes
 * @Date 2023/3/21 11:04
 * @PackageName:com.haynes.reggie.controller
 * @ClassName: DishController
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService flavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody @NotNull DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
//       清理某个分类下的菜品缓存数据
        redisTemplate.delete(PublicKey.DishKey(dishDto));
        return R.success("添加成功！");
    }

    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
//        创建分页对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
//      创建VO的分页对象
        Page<DishDto> dishDtoPage = new Page<>();

//        添加条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        排序
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishLambdaQueryWrapper.eq(Dish::getIsDeleted,0);

//        模糊查询
        dishLambdaQueryWrapper.like(name != null, Dish::getName, name);


//        1.查询到所有的菜品信息
        dishService.page(dishPage, dishLambdaQueryWrapper);
//        2.将菜品分页对象的属性复制到菜品Vo对象中 Page<DishDto>,且不包含records属性
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
//      3.获取到所有的菜品信息
        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = new ArrayList<>();

//      遍历菜品信息并添加到列表中
        for (Dish item : records) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);

            Category category = categoryService.getById(item.getCategoryId());
            String categoryName = category.getName();
            dto.setCategoryName(categoryName);

            list.add(dto);
        }


//        将查询到的数据赋值给VO的分页
        dishDtoPage.setRecords(list);
//      返回VO的分页对象
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> getDish(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return  R.success(dishDto);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
//        删除指定Key的分类下的菜品缓存数据
        redisTemplate.delete(PublicKey.DishKey(dishDto));

        dishService.updateByIdWithFlavor(dishDto);
        return R.success("更新菜品信息成功！");
    }

    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids){
        dishService.updateStatusByIdBatch(status, ids);
        return R.success("商品状态修改成功!");
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.removeByIdBatch(ids);
        return R.success("删除菜品信息成功!");
    }

    /**
     * 根据分类ID查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(DishDto dish){
        List<DishDto> dishDtoList=null;

//        设置一个Key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();

//        获取缓存中分类下的菜品
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(PublicKey.DishKey(dish));
//        判断是否存在，不存在查询数据库，存在则直接返回
        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        dishWrapper.eq(Dish::getStatus,1);
        dishWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(dishWrapper);

        dishDtoList = dishList.stream().map((item)->{
            DishDto dishDto  = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Category category = categoryService.getById(item.getCategoryId());
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
//            对应菜品ID的口味数据
            List<DishFlavor> dishFlavorList = flavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;

        }).collect(Collectors.toList());

//        不存在则查询数据库，把数据放进缓存当中
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
